from PIL import Image, ImageDraw, ImageFont
import random, time

from flask import url_for


class VerifyCode():
    def __init__(self):
        self.codeId = ""  # 唯一标志一个验证码
        self.codeUrl = ""  # 验证码路径
        self.code = ""  # 验证码
        self.get_code()

    # 取出随机字符
    def get_random_char(self):
        string_list = []
        string_list.append(chr(random.randint(65, 90)))  # 大写字母
        string_list.append(chr(random.randint(97, 122)))  # 小写字母
        string_list.append(str(random.randint(1, 9)))  # 数字,0和o太相似，排除0
        return random.choice(string_list)

    # 生成随机颜色
    def random_color_line(self):
        R = random.randint(18, 128)
        G = random.randint(18, 128)
        B = random.randint(18, 128)
        return (R, G, B)

    # 生成随机颜色
    def random_color_char(self):
        # 缩小RGB各分量的取值范围，使其更偏向于深色，这里取值范围可以根据实际需求再调整
        R = random.randint(0, 150)
        G = random.randint(0, 150)
        B = random.randint(0, 150)
        return (R, G, B)

    # 生成在图形上的随机坐标值
    def get_rand_point(self, image_obj):
        width, height = image_obj.size
        return (random.randint(0, width), random.randint(0, height))

    # 生成干扰线
    def draw_line(self, image_obj, num):
        draw = ImageDraw.Draw(image_obj)
        for i in range(num):
            draw.line([self.get_rand_point(image_obj), self.get_rand_point(image_obj)], fill=self.random_color_line())
        del draw

    def get_code(self):
        # 创建一个新的图像对象
        Image_captcha = Image.new('RGB', (200, 100), (232, 232, 232))
        # 画干扰线
        self.draw_line(Image_captcha, 8)
        # 加载字体，确保字体文件在同一目录下
        try:
            font_china = ImageFont.truetype('../app/resources/verify_code.ttf', 60)  # 字体文件
        except IOError:
            print("没有发现字体文件，请确保字体文件的路径正确。")
            exit()

        # 创建画笔对象
        draw_pen = ImageDraw.Draw(Image_captcha)

        # 画验证码字符
        for i in range(5):
            verify_char = self.get_random_char()
            self.code += verify_char
            color_char = self.random_color_char()
            for j in range(3):
                draw_pen.text((38 * i + j + 10, 25 + j), verify_char, color_char, font=font_china)
        del draw_pen  # 显式删除画笔对象

        self.codeId = "t" + str(time.time()).replace(".", "")[:11]  # codeId为时间错，截取前11位数字，前缀位“t”
        fileName = "tmp/" + self.codeId + ".jpg"
        try:
            Image_captcha.save("static/" + fileName)
            self.codeUrl = url_for('static', filename=fileName)
        except:
            print("保存验证码失败")


if __name__ == "__main__":
    v = VerifyCode()
    print(v.codeId)
    print(v.code)
